const appointmentService = require('../../../services/appointment');
const util = require('../../../utils/util');

Page({
  data: {
    tabs: ['待确认', '已确认', '已完成', '已取消'],
    currentTab: 0,
    appointments: [],
    loading: true,
    page: 1,
    size: 10,
    hasMore: true,
    staffInfo: null
  },

  onLoad: function () {
    this.loadStaffInfo();
    this.loadAppointments(true);
  },

  onShow: function () {
    if (this.data._isShown) {
      this.refresh();
    }
    this.data._isShown = true;
  },

  // 加载医生信息
  loadStaffInfo: function () {
    const app = getApp();
    const staffInfo = app.getStaffInfo();
    if (staffInfo) {
      this.setData({
        staffInfo
      });
    } else {
      // 如果没有医生信息，返回登录页
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/staff-login',
        });
      }, 1500);
    }
  },

  // 切换标签页
  switchTab: function (e) {
    const index = e.currentTarget.dataset.index;
    if (index === this.data.currentTab) return;

    this.setData({
      currentTab: index,
      appointments: [],
      page: 1,
      hasMore: true
    });

    this.loadAppointments(true);
  },

  // 加载预约列表
  loadAppointments: function (showLoading = false) {
    if (!this.data.hasMore) return;
    if (!this.data.staffInfo) return;

    const staffId = this.data.staffInfo.id;
    const status = this.data.currentTab;
    const page = this.data.page;
    const size = this.data.size;

    if (showLoading) {
      wx.showLoading({
        title: '加载中...',
      });
    }

    this.setData({
      loading: true
    });

    appointmentService.getStaffAppointments(status, page, size)
      .then(res => {
        // 格式化时间
        const formattedAppointments = res.records.map(item => {
          return {
            ...item,
            formattedTime: util.formatDateTime(new Date(item.appointmentTime.replace(' ', 'T')))
          };
        });

        // 合并数据
        const appointments = page === 1 
          ? formattedAppointments 
          : [...this.data.appointments, ...formattedAppointments];

        this.setData({
          appointments,
          loading: false,
          hasMore: res.records.length === size,
          page: page + 1
        });

        if (showLoading) {
          wx.hideLoading();
        }

        // 停止下拉刷新
        wx.stopPullDownRefresh();
      })
      .catch(err => {
        console.error('获取预约列表失败', err);
        this.setData({
          loading: false
        });

        if (showLoading) {
          wx.hideLoading();
        }

        // 停止下拉刷新
        wx.stopPullDownRefresh();

        // 显示错误信息
        wx.showToast({
          title: '获取预约列表失败',
          icon: 'none'
        });
      });
  },

  // 刷新数据
  refresh: function () {
    this.setData({
      page: 1,
      appointments: [],
      hasMore: true
    });
    this.loadAppointments(true);
  },

  // 跳转到预约详情
  navigateToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/staff/appointments/detail?id=${id}`
    });
  },

  // 确认预约
  confirmAppointment: function (e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认预约',
      content: '确定要接受这个预约吗？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          });

          appointmentService.confirmAppointment(id)
            .then(() => {
              wx.hideLoading();
              wx.showToast({
                title: '预约已确认',
                icon: 'success'
              });
              // 刷新列表
              this.refresh();
            })
            .catch(err => {
              wx.hideLoading();
              console.error('确认预约失败', err);
              wx.showToast({
                title: err.message || '确认预约失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 完成预约
  completeAppointment: function (e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '完成预约',
      content: '确定要标记这个预约为已完成吗？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          });

          appointmentService.completeAppointment(id)
            .then(() => {
              wx.hideLoading();
              wx.showToast({
                title: '预约已完成',
                icon: 'success'
              });
              // 刷新列表
              this.refresh();
            })
            .catch(err => {
              wx.hideLoading();
              console.error('完成预约失败', err);
              wx.showToast({
                title: err.message || '完成预约失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 拒绝预约
  rejectAppointment: function (e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '拒绝预约',
      content: '确定要拒绝这个预约吗？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          });

          appointmentService.rejectAppointment(id)
            .then(() => {
              wx.hideLoading();
              wx.showToast({
                title: '已拒绝预约',
                icon: 'success'
              });
              // 刷新列表
              this.refresh();
            })
            .catch(err => {
              wx.hideLoading();
              console.error('拒绝预约失败', err);
              wx.showToast({
                title: err.message || '拒绝预约失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 创建诊断意见
  createMedicalRecord: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/staff/medical/create?appointmentId=${id}`
    });
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadAppointments();
    }
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.refresh();
  }
}); 